package com.alarm.ecp;

import com.alarm.ecp.constant.EventConstant;
import com.alarm.ecp.pojo.EventPO;
import com.alarm.ecp.utils.KafkaUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;

/**
 * 用户在15分钟内的行为路径是"登录-领券-下单"(明显薅羊毛行为特征)
 * 组合模式
 */
public class ClipCouponsRoute {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStream<EventPO> eventStream = KafkaUtil.read(args, env);

        // 有事件范围匹配需要加水印
        KeyedStream<EventPO, Integer> eventPOIntegerKeyedStream = eventStream.assignTimestampsAndWatermarks(WatermarkStrategy.<EventPO>forBoundedOutOfOrderness(Duration.ofSeconds(5)).withTimestampAssigner((event, timestamp) -> event.getTimeStamp())).keyBy((KeySelector<EventPO, Integer>) EventPO::getUserId);

        Pattern<EventPO, EventPO> pattern = Pattern
                // 过滤登录行为事件
                .<EventPO>begin("login")
                .where(new SimpleCondition<EventPO>() {
                    @Override
                    public boolean filter(EventPO eventPO) throws Exception {
                        return EventConstant.LOGIN_SUCCESS.equals(eventPO.getEventType());
                    }
                })
                // 宽松近邻：过滤领取优惠券行为事件
                .followedBy("receive")
                .where(new SimpleCondition<EventPO>() {
                    @Override
                    public boolean filter(EventPO eventPO) throws Exception {
                        return EventConstant.COUPON_RECEIVE.equals(eventPO.getEventType());
                    }
                })
                // 宽松近邻：过滤使用优惠券行为事件
                .followedBy("use")
                .where(new SimpleCondition<EventPO>() {
                    @Override
                    public boolean filter(EventPO eventPO) throws Exception {
                        return EventConstant.COUPON_USE.equals(eventPO.getEventType());
                    }
                })
                // 模式有效时间：15分钟内
                .within(Time.minutes(15));

        env.execute("ClipCouponsRoute");
    }
}
